package com.example.ccj.u.update;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.view.Gravity;
import android.view.View;

import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.sdk.android.oss_android_sdk.BuildConfig;
import com.example.ccj.b.c.dialog.DownLoadDialog;
import com.example.ccj.b.c.dialog.SureOrCancelDialog;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.AppUtils;
import com.example.ccj.u.GsonUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.server.Result;


import java.io.File;
import java.util.Objects;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
* app更新
* 驰郡
* wechat:chijun9
* 2023/11/21
*/
public class AppUpdateUtil {

    public static void handleResult(Context context, Result result, UpdateListener updateListener){

        if (result.getVersion() == 0) {
            LogUtils.d("服务器返回更新信息：" + 0);
            if (updateListener != null) updateListener.onUpdate(false,false,false);
        } if (result.getVersion() == 1) {
            LogUtils.d("服务器返回更新信息：" + 1);
            mastUpdate(context,result,updateListener);
        } if (result.getVersion() == -1) {
            LogUtils.d("服务器返回更新信息：" + -1);
            noMastUpdate(context,result,updateListener);
        }

        AppUtils.getAppVersionCode();
    }

    /**
     * 强制更新
     * @param context 上下文
     * @param result 服务器返回数据
     * @param updateListener 未更新回调
     */
    private static void mastUpdate(Context context, Result result,UpdateListener updateListener){
        AppVersion appVersion = JSON.parseObject(result.getData(),AppVersion.class);
        LogUtils.d("mastUpdate: " + appVersion);

        LogUtils.d("mastUpdate: " + appVersion);
        if (appVersion == null) {
            LogUtils.d("强制更新APP服务器版本为空：");
            return;
        }
        LogUtils.d(StringUtils.format("强制更新服务器版本:[?],服务器版本信息：[?]",appVersion.version,appVersion.message));
        if (appVersion.message != null) {
            LogUtils.d("mastUpdate: ",appVersion.message);
            SureOrCancelDialog dialog = new SureOrCancelDialog(context);
            LogUtils.d("mastUpdate: ",appVersion.message);
            appVersion.message = appVersion.message.replace("\\n","\n");
            dialog.setCenterText("监测到更新包，本次更新为强制更新!\n本地版本号："+getVersion(context)+"\n最新版本号："+appVersion.version+"\n最近一次更新内容\n"+appVersion.message).setTextColor(Color.RED);
            dialog.getmTvCenterText().setGravity(Gravity.START);
            dialog.setCancelable(false);//不可关闭
            dialog.setButtonSureText("确定更新");
            dialog.setButtonSureClick(v -> {
                dialog.dismiss();
                doDownload(context,appVersion.url,updateListener,true);
            });
            dialog.setButtonCancelText("退出");
            dialog.setButtonCancelClick(v -> {
                dialog.dismiss();
                AppUtils.exitApp();
                if (updateListener != null) updateListener.onUpdate(true,true,false);
            });
            dialog.show();
        }
    }

    private static void noMastUpdate(Context context, Result result,UpdateListener updateListener){

        AppVersion appVersion = JSON.parseObject(result.getData(),AppVersion.class);
        if (appVersion == null) {
            LogUtils.d("非强制更新APP服务器版本为空：");
            return;
        }
        LogUtils.d(StringUtils.format("强制更新服务器版本:[?],服务器版本信息：[?]",appVersion.version,appVersion.message));
        if (appVersion.message != null) {
            LogUtils.d("进入更新流程：");

            SureOrCancelDialog dialog = new SureOrCancelDialog(context);
            appVersion.message = appVersion.message.replace("\\n","\n");
            dialog.setCenterText("监测到更新包，是否下载更新？\n本地版本号："+getVersion(context)+"\n最新版本号："+appVersion.version+"\n最近一次更新内容\n"+appVersion.message).setTextColor(Color.RED);
            dialog.getmTvCenterText().setGravity(Gravity.START);
            dialog.setCancelable(true);//不可关闭
            dialog.setButtonSureText("更新");
            dialog.setButtonSureClick(v -> {
                dialog.dismiss();
                doDownload(context,appVersion.url,updateListener,false);
            });
            dialog.setButtonCancelText("取消");
            dialog.setButtonCancelClick(v -> {
                dialog.dismiss();
                if (updateListener != null) updateListener.onUpdate(true,false,false);
            });
            dialog.show();
            LogUtils.d("已启动dialog" );

        }
    }


    /**
     * 下载更新文件
     * @param url 文件地址
     */
    private static void doDownload(Context context,String url,UpdateListener updateListener,boolean isMast){
        DownLoadDialog downLoadDialog = new DownLoadDialog(context,100);
        downLoadDialog.show();
        String parentPath = "";
        try {
            parentPath = context.getExternalFilesDir(null).getPath();
        } catch (Exception e) {
            LogUtils.d("doDownload() Exception: " + e.getMessage());
        }

        LogUtils.d( "doDownload() parentPath: " + parentPath);

        File file = new File(parentPath, DownloadUtil.getNameFromUrl(url));
        final String filePath = file.getAbsolutePath();

        //如果已有文件，删除
        if (file.exists()) {
            LogUtils.d( "doDownload() delete APK: " );
            boolean isDelete = file.delete();
        }

        try {
            //开始异步下载
            Observable.create((ObservableOnSubscribe<Integer>) emitter -> DownloadUtil.get().download(url, filePath, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess(String path) {
                    emitter.onComplete();
                }

                @Override
                public void onDownloading(int progress) {
                    emitter.onNext(progress);
                }

                @Override
                public void onDownloadFailed(String error) {
                    emitter.onError(new Exception(error));
                }
            })).subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Integer>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Integer integer) {
                            downLoadDialog.setSpeed(integer);
                        }

                        @Override
                        public void onError(Throwable e) {
                            downLoadDialog.dismiss();
                            SureOrCancelDialog dialog = new SureOrCancelDialog(context);
                            dialog.setCenterText("下载更新失败"+e.getMessage());
                            dialog.setButtonSureText("取消");
                            dialog.setButtonSureClick(v -> {
                                if (isMast) {
                                    updateListener.onUpdate(true,true,false);
                                } else {
                                    dialog.dismiss();
                                }
                            });
                            dialog.setButtonContinueText("重新下载");
                            dialog.setButtonContinueClick(v -> {
                                dialog.dismiss();
                                doDownload(context,url,updateListener,isMast);
                            });

                            dialog.show();
                        }

                        @Override
                        public void onComplete() {
                            downLoadDialog.dismiss();
                            LogUtils.d( "onDownloadSuccess() 下载成功: " + "保存位置：\\n\"+file.getPath()+\"\\n点击确定开始安装，如安装失败，请手动安装！！！\"");
                            installApk(context,file);

                            SureOrCancelDialog dialog = new SureOrCancelDialog(context);
                            dialog.setCenterText("文件下载成功，保存位置：\n"+file.getPath()+"\n点击确定开始安装，如安装失败，请手动安装！！！");
                            dialog.setButtonSureText("安装");
                            dialog.setCancelable(false);
                            dialog.setButtonSureClick(v -> {
                                dialog.dismiss();
                                //开始安装
                                AppUtils.installApp(file);

                            });

                            dialog.setButtonCancelText("退出");
                            dialog.setButtonCancelClick(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
//                                    ActivityUtils.finishAllActivities();
                                    updateListener.onUpdate(true,true,false);
                                }
                            });
                            dialog.show();
                        }
                    });
        } catch (Exception e) {
            downLoadDialog.dismiss();
            SureOrCancelDialog dialog = new SureOrCancelDialog(context);
            dialog.setCenterText("下载更新失败"+e.getMessage());
            dialog.setButtonSureText("确定");
            dialog.setButtonSureClick(v -> dialog.dismiss());
            dialog.show();
        }
    }

    //安装app
    private static void installApk(Context context, File file) {
//        logUtil.d( "onDownloadSuccess() 开始安装: " + "");
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        Uri data;
//        //7.0以上安卓系统安装app需要通过fileProvider（需要在AndroidManifest.xml声明）
//        data = FileProvider.getUriForFile(context, "com.chijun.tools.tools", file);
//        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//
//        intent.setDataAndType(data, "application/vnd.android.package-archive");
//        context.startActivity(intent);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        //L.i("安装路径=="+downloadApk);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName()  + ".fileProvider", file);//这句很重要
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }


    /**
     * 获取当前版本
     */
    public static int getVersion(Context context){
        int versionName = 0;
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }


    public interface UpdateListener{
        void onUpdate(boolean needUpdate,boolean isMast,boolean isUpdate);
    }
}
